package com.ifcar.app.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.common.CommentFragment;
import com.ifcar.app.bean.PhotoInfo;
import com.ifcar.app.db.DBUtils;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.rss.GetComments;
import com.ifcar.app.util.CollectUtil;
import com.ifcar.app.util.Constant;
import com.ifcar.app.util.HttpUtils;
import com.ifcar.app.util.NeteaseHttpClient;
import com.ifcar.app.util.PicUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.NewsImageViewer;
import com.ifcar.app.view.ImageViewer.OnItemListener;
import com.ifcar.app.activity.R;

public class ImageSwitcherActivity extends BaseActivity implements OnItemListener/*AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory*/ {

	private View textContent;
    private RelativeLayout top_relative;
	private FrameLayout bottom_framelayout;
	private View imagerandombar;
	private TextView text_setname;
	private TextView text_imgsum;
	private TextView text_imgtitle;
	private ImageButton button_download;
	private ImageButton button_comment;
	private ImageButton button_collect;
	private NewsImageViewer mImageViewer;
	public int g_position = 0;//当前图片在图集的位置
	public List<PhotoInfo> photolist;
	public String imgsum="0";
	public String setid = "0";
	public String channel = "0096";
	
	private String imageTitle;
	private String clientcover;
	private String collectId;
	
	public int initindex = 0;
	private boolean showtoolbar = true;
	private boolean fromCollect = false;
	private SharedPreferences set_prefs;
	private String account="";
	private String setcoverurl = "";
	private String seturl = "";
	private String setname = "";
	
	//--------------跟贴相关----------------//
	private ImageView reply_img_button;
	private View bottom_buttonlayout;
	private View reply_edittext_layout;
	private EditText replyEditText;
	private Button reply_button;
	private Animation slideTopIn;
	private Animation slideTopOut;
	private InputMethodManager imm;
	
	private Button detailPageReply;
	private String quote = "";
	private String replyCountNum = "0";
	private boolean replyWithQuote = false;
	
	private ViewGroup mContainer;

	private FrameLayout detailPageOriginal;
	private RelativeLayout detailPageComments;
	
	private Button backOriginal;
	private boolean isshowimg = true;
	
	private JSONObject jobj = null;
	private String boardid = "";
	private String postid = "";
	private String commentUrl = "";
	
    private HashMap<String, Object> moreMap = new HashMap<String, Object>();
    private HashMap<String, Object> docIDListMap = new HashMap<String, Object>();
    private ArrayList<String> docIDList = new ArrayList<String>();
    private ArrayList<String> specailIDList = new ArrayList<String>();
	
	private boolean isComment = false;
	private ImageView hide_open_desc;
	
	private ThemeSettingsHelper themeSettingsHelper;
	private Context theContext;
	
    private List<ResolveInfo> sharelist;
    private boolean fromHead = false;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.image_switcher_layout);

		theContext = this;
        themeSettingsHelper = getThemeSettingsHelper();
		findView();
		setListener();
		detailPageReply.setVisibility(View.GONE);
        Bundle bundle = this.getIntent().getExtras();
        setid = bundle.getString("setid");
        String tempChannel = bundle.getString("channel");
        if(!TextUtils.isEmpty(tempChannel)){
            channel = tempChannel;
        }
        boardid = bundle.getString("boardid");
        postid = bundle.getString("postid");
        if(null==boardid) boardid = "";
        if(null==postid) postid = "";
        
        imageTitle =  bundle.getString("imgTitle");
        clientcover =  bundle.getString("clientcover");
        fromHead = bundle.getBoolean("fromHead", false);
        imgsum =  bundle.getString("imgsum");
        initindex = bundle.getInt("currentindex", 0);
        fromCollect = bundle.getBoolean("fromCollect", false);
	      
        //加载用户名和密码
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		account = set_prefs.getString("account", "");
		boolean downpic = set_prefs.getBoolean("downpic", false);
		isshowimg = Tools.isshowimg(downpic, this);
        g_position = initindex;
        
        currentSizeId = set_prefs.getInt("currentSizeId", 2);
        lastSizeId = currentSizeId;
        
        imm = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
		
		updateData();
		setMenu();
		
		setAnimationLinstener();
		
		if(fromCollect){
			detailPageOriginal.setVisibility(View.GONE);
			detailPageComments.setVisibility(View.VISIBLE);
			detailPageComments.requestFocus();
		}

		sharelist = Tools.getShareTargets(this,"message/rfc822");
	}
	
	private void findView(){	    
		text_setname = (TextView)findViewById(R.id.text_setname);
		text_imgsum = (TextView)findViewById(R.id.text_imgsum);
		text_imgtitle = (TextView)findViewById(R.id.text_imgtitle);
		textContent = findViewById(R.id.text_content);
		button_download = (ImageButton)findViewById(R.id.button_download);
		button_collect = (ImageButton) findViewById(R.id.image_collect);
		button_comment = (ImageButton)findViewById(R.id.button_comment);
		
		button_download.setEnabled(false);
		button_collect.setEnabled(false);
		button_comment.setEnabled(false);

		top_relative = (RelativeLayout)findViewById(R.id.top_relative);
        imagerandombar = findViewById(R.id.imagerandombar);
        bottom_framelayout = (FrameLayout)findViewById(R.id.bottom_framelayout);
       
        mImageViewer = (NewsImageViewer)findViewById(R.id.flipper);
        mImageViewer.setOnItemListener(this);
        slideTopIn = AnimationUtils.loadAnimation(this, R.anim.slide_top_in);
		slideTopOut = AnimationUtils.loadAnimation(this, R.anim.slide_top_out);
		
		// 整个页面
		mContainer = (ViewGroup) findViewById(R.id.container);
		detailPageOriginal = (FrameLayout)findViewById(R.id.image_page_original);
		detailPageComments = (RelativeLayout)findViewById(R.id.detail_page_comments);
		
		
		/**跟贴页面*/
		backOriginal = (Button) detailPageComments.findViewById(R.id.show_comments_back_original);
		backOriginal.setText("  原图  ");
		backOriginal.setTextColor(getResources().getColor(R.color.white));
		
        bottom_buttonlayout = findViewById(R.id.bottom_buttonlayout);
        reply_edittext_layout = findViewById(R.id.reply_edittext_layout);
        replyEditText = (EditText)reply_edittext_layout.findViewById(R.id.reply_edittext);
        reply_button = (Button)reply_edittext_layout.findViewById(R.id.reply_button);
        reply_img_button = (ImageView) bottom_buttonlayout.findViewById(R.id.reply_img_button);
		detailPageReply = (Button) findViewById(R.id.detail_page_reply);
		detailPageReply.setClickable(false);
		
		hide_open_desc = (ImageView)findViewById(R.id.hide_open_desc);
	}
	
	
	private void setListener(){
		progressDialog = new ProgressDialog(ImageSwitcherActivity.this);
		progressDialog.setMessage("正在发表跟贴...");
        progressDialog.setCancelable(true);
        
        button_download.setOnClickListener(button_download_ClickListener);
        button_comment.setOnClickListener(button_comment_ClickListener);  
        
        reply_img_button.setOnClickListener(replay_img_buttonlistener);
        reply_button.setOnClickListener(replyClickListener);
        
        detailPageReply.setOnClickListener(buttonClickListener);
        backOriginal.setOnClickListener(buttonClickListener);
		
		button_collect.setOnClickListener(new ImageButton.OnClickListener() { // 图片收藏
			@Override
			public void onClick(View v) {
				if(autoId!=-1){
					cu.deleteAlreadyCollect(autoId, CollectUtil.COLLECT_PICTURES);
					Toast.makeText(ImageSwitcherActivity.this, getResources().getString(R.string.cancel_collect), Toast.LENGTH_SHORT).show();
					themeSettingsHelper.setImageViewSrc(theContext, button_collect, R.drawable.collect_button_selector);
				}else{
					
					StringBuilder img = new StringBuilder();
			    	img.append(clientcover);

			    	Long flag = cu.doCollectObject(img.toString(), imageTitle, collectId, CollectUtil.COLLECT_PICTURES);
					if(flag == -1){
						themeSettingsHelper.setImageViewSrc(theContext, button_collect, R.drawable.collect_button_selector);
						Toast.makeText(ImageSwitcherActivity.this, getResources().getString(R.string.fail_collect),Toast.LENGTH_SHORT).show();
					}else{
						themeSettingsHelper.setImageViewSrc(theContext, button_collect, R.drawable.collect_cancel_selector);
						Toast.makeText(ImageSwitcherActivity.this, getResources().getString(R.string.success_collect), Toast.LENGTH_SHORT).show();
					}
				}
				autoId = cu.getAlreadyCollect(clientcover, collectId, CollectUtil.COLLECT_PICTURES);
			}
		});
		
		hide_open_desc.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(text_imgtitle.getVisibility() == View.VISIBLE){
					text_imgtitle.setVisibility(View.GONE);
					textContent.setVisibility(View.GONE);
					hide_open_desc.setImageDrawable(ImageSwitcherActivity.this.getResources().getDrawable(R.drawable.open_image_desc));
				}else{
					text_imgtitle.setVisibility(View.VISIBLE);
					if("".equalsIgnoreCase(text_imgtitle.getText().toString())){
					    textContent.setVisibility(View.GONE);
					}else{
					    textContent.setVisibility(View.VISIBLE);
					}
					hide_open_desc.setImageDrawable(ImageSwitcherActivity.this.getResources().getDrawable(R.drawable.hide_image_desc));
				}
			}
		});
		
		imagerandombar.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if(text_imgtitle.getVisibility() == View.VISIBLE){
                    text_imgtitle.setVisibility(View.GONE);
                    textContent.setVisibility(View.GONE);
                    hide_open_desc.setImageDrawable(ImageSwitcherActivity.this.getResources().getDrawable(R.drawable.open_image_desc));
                }else{
                    text_imgtitle.setVisibility(View.VISIBLE);
                    if("".equalsIgnoreCase(text_imgtitle.getText().toString())){
                        textContent.setVisibility(View.GONE);
                    }else{
                        textContent.setVisibility(View.VISIBLE);
                    }
                    hide_open_desc.setImageDrawable(ImageSwitcherActivity.this.getResources().getDrawable(R.drawable.hide_image_desc));
                }
            }
        });
		
	}
	
	// 分享文章获取正文
	private String getShareHtml(String shorturl, int type) {
		// TODO Auto-generated method stub
		StringBuilder html = new StringBuilder();
		
		html.append("我在网易新闻手机客户端，发现了图集：<html><head></head><body style=\"margin:0px; padding:0px;\">")
			.append("<center><div style=\"color:#464646;font-size:18px;font-weight:bold;\" >")
			.append(setname).append("</div>")/*.append("<p>图集地址：<a href=\"").append(seturl).append("\">")
			.append(seturl).append("</a></p>").append("<p>原图地址：<a href=\"").append(shorturl).append("\">")
			.append(shorturl).append("</a></p>")append("</div>").*/;
		
		if(type==4){
			html.append("<--insert-->");
		}
		html.append("</body></html>");
		
		return html.toString();
	}
	
	//获取跟贴信息
	private String getCommentHtmlString(String shorturl, int type) {
		// TODO Auto-generated method stub
		StringBuilder html = new StringBuilder();
		
		html.append("我在网易新闻手机客户端，发现了跟贴：<html><head></head><body style=\"margin:0px; padding:0px;\">")
			.append("<center><div style=\"color:#464646;font-size:18px;font-weight:bold;\" >") 
			.append(setname).append("</div>").append("<p>跟贴地址：<a href=\"").append(shorturl).append("\">")
			.append(shorturl).append("</a></p>").append("</div>");
		
		if(type == 4){
			html.append("<--insert-->");
		}
		html.append("</body></html>");
		return html.toString();
	}
	
	/**动画监听*/
	private void setAnimationLinstener(){
		
		slideTopOut.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				bottom_buttonlayout.setVisibility(View.GONE);	
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				
			}
		});
	}
	
	
	/**原图 跟帖 切换*/
	private View.OnClickListener buttonClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			
			if(menuWindow != null)menuWindow.dismiss();
			if(config != Configuration.ORIENTATION_PORTRAIT) return;
			
			if(!fromCollect) backOriginal.setVisibility(View.GONE);
			
			if (replyCountNum != null && (replyCountNum.equals("0")||replyCountNum.equals("-1"))) {
				Toast.makeText(ImageSwitcherActivity.this, "目前没有跟贴", Toast.LENGTH_SHORT).show();
				return;
			}
			
			if (imm != null) {
				imm.hideSoftInputFromWindow(replyEditText.getWindowToken(), 0);
			}
			
			switch (v.getId()) {
			case R.id.show_comments_back_original:
				switchNewsAndComments(false);
				break;
			case R.id.detail_page_reply:
				//TODO 暂时使用这种方法解决
				if ("跟贴".equals(detailPageReply.getText())) {
					return;
				}
				switchNewsAndComments(true);
				break;
			}
			
			
		}
	};
	
	/**
	 * 切换正文和跟帖
	 * @param isNews2Comment
	 */
	private void switchNewsAndComments(boolean isNews2Comment){
		
		if(isNews2Comment){ // 正文切换至跟帖
			
            CommentFragment fragment = (CommentFragment) getSupportFragmentManager()
                    .findFragmentByTag("detail_comment");
            if (fragment == null) {
                Bundle bundle = new Bundle();
                bundle.putString(CommentFragment.BOARD_ID, boardid);
                bundle.putString(CommentFragment.DOC_ID, postid);
                bundle.putString(CommentFragment.DOC_TITLE, setname);
                bundle.putString(CommentFragment.COMMENT_URL, commentUrl);
                bundle.putInt(CommentFragment.COLLECT_TYPE, CollectUtil.COLLECT_PIC_COMMENT);

                fragment = (CommentFragment) addFragmentByTag(R.id.common_comments_content_layout,
                        CommentFragment.class, "detail_comment", bundle);
            }
            fragment.setTextSize(getLastTextSize());
            fragment.selectInTab();
	        isComment = true;
		    Animation animation = AnimationUtils.loadAnimation(this,
                    R.anim.fade_in_fast);
		    detailPageComments.setVisibility(View.VISIBLE);
		    detailPageOriginal.setVisibility(View.GONE);
		    detailPageComments.findViewById(R.id.common_comments_content_layout).startAnimation(animation);
		}else{
            CommentFragment fragment = (CommentFragment)getSupportFragmentManager().findFragmentByTag("detail_comment");
            if (fragment != null) {
                fragment.unSelectInTab();
            }
			ImageSwitcherActivity.this.setRequestedOrientation(-1);
			isComment = false;
			
		    detailPageComments.setVisibility(View.GONE);
		    detailPageOriginal.setVisibility(View.VISIBLE);
		}
	}
	
	
	public void goBackClick(View view){
		if(fromCollect){ // 收藏
			if(view.getId() == R.id.go_back_from_original){
				switchNewsAndComments(true);
			}else if(view.getId() == R.id.go_back_from_comment){
				finish();
			}
		}else{ // 其他
			if(view.getId() == R.id.go_back_from_original){
				finish();
			}else if(view.getId() == R.id.go_back_from_comment){
				switchNewsAndComments(false);
			}
		}
	}
	
	/**发表跟贴*/
	private View.OnClickListener replyClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			if("".equals(postid)||"".equals(boardid)){
				Toast.makeText(ImageSwitcherActivity.this, "此图集没有跟贴", Toast.LENGTH_SHORT).show();
				return;
			}
						
			account = set_prefs.getString("account", "");
			if("".equals(account)){
			    if (replyEditText.getText() != null
                        && !replyEditText.getText().toString().equals("")) {
                    
                    if(replyEditText.getText().toString().length()<=1 ||
                            replyEditText.getText().toString().length()>1000){
                        Toast.makeText(ImageSwitcherActivity.this, "回复请在2-1000字内", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    
                    Intent Loginintent = new Intent(ImageSwitcherActivity.this, AccountLogin.class);
                    Loginintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Bundle bundle = new Bundle();
                    
                    bundle.putBoolean("isreply", true);
                    bundle.putBoolean("replyWithQuote", replyWithQuote);
                    
                    bundle.putString("replydocid", postid);
                    bundle.putString("replyquote", quote);
                    bundle.putString("replyBoard", boardid);
                    bundle.putString("replycontent", replyEditText.getText().toString());
                    Loginintent.putExtras(bundle);
                    ImageSwitcherActivity.this.startActivity(Loginintent);
                    
                }else{
                    
                    Toast.makeText(ImageSwitcherActivity.this, "不能发空消息", Toast.LENGTH_SHORT).show();
                }
				

			}else{
			    if (replyEditText.getText() != null
                        && !replyEditText.getText().toString().equals("")) {
                    
                    if(replyEditText.getText().toString().length()<=1 ||
                            replyEditText.getText().toString().length()>1000){
                        Toast.makeText(ImageSwitcherActivity.this, "回复请在2-1000字内", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    final String board = boardid;
                    final String did = postid;
                    final String text = replyEditText.getText().toString();
                    final String a = account;
                    postCommentThread(board, did, text, a, false, "", isDetailPageReply);

                } else {
                    Toast.makeText(ImageSwitcherActivity.this, "不能发空消息", Toast.LENGTH_SHORT).show();
                }

            }		
			
		}
	};
	
	private final int isCommentsPageReply = 0;
	private final int isDetailPageReply = 1;
	private void postCommentThread(final String board, final String docid,
			final String text, final String account, final boolean replyWithQuote, 
			final String quote, final int type) {
		
		progressDialog.show();
		new Thread() {
			public void run() {
				Message msg = new Message();
				msg.what = 15;		
				msg.arg1 = type;
				if(replyWithQuote) {
					msg.obj = GetComments.postComment(board, docid, quote, text, account, "新闻客户端用户",
							"0.0.0.0", "false",ImageSwitcherActivity.this);
				} else {
					msg.obj = GetComments.postComment(board, docid, text, account, "新闻客户端用户",
							"0.0.0.0", "false",ImageSwitcherActivity.this);
				}

				handler.sendMessage(msg);
				
			}
		}.start();

	}
	
	
	
	 @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        boolean downpic = set_prefs.getBoolean("downpic", false);
        isshowimg = Tools.isshowimg(downpic, this);
        
    }

    protected void onRestart() {
	    	setCollectAttibute();
			super.onRestart();
		}
	
	private void setCollectAttibute(){
		cu = new CollectUtil(this);
		JSONObject j = new JSONObject();
		try {
			j.put("setId", setid);
			j.put("num", imgsum);
			j.put("channel", channel);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		collectId = j.toString();
		autoId = cu.getAlreadyCollect(clientcover, collectId, CollectUtil.COLLECT_PICTURES);
			
		if(autoId!=-1)
		    themeSettingsHelper.setImageViewSrc(theContext, button_collect, R.drawable.collect_cancel_selector);
		else
		    themeSettingsHelper.setImageViewSrc(theContext, button_collect, R.drawable.collect_button_selector);
	}
	
	/**点击更贴图标*/
	private OnClickListener replay_img_buttonlistener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if(replyCountNum.equals("-1")){
				Toast.makeText(ImageSwitcherActivity.this, "此图集没有跟贴", Toast.LENGTH_SHORT).show();
			}else{
				
				replyEditText.requestFocus();
				
		        if (imm != null) {
		            imm.showSoftInput(replyEditText, 0);
		        }
		        bottom_buttonlayout.setVisibility(View.GONE);
				reply_edittext_layout.setVisibility(View.VISIBLE);
				//top_relative.startAnimation(slideTopOut);
			}
			
		}
	};
	
	
	
	private boolean isRefresh = false;
	private void updateData(){
	    View currentView = mImageViewer.getCurrentView();
	    View loadingBar = currentView.findViewById(R.id.loadingbar);
	    loadingBar.setVisibility(View.VISIBLE);
	    
		photolist = new ArrayList<PhotoInfo>();
		
		new Thread(){
			public void run() {
				
				String rst = getPhotosetJson(channel,setid);
				if("".equals(rst)){				
				    String photoseturl = String.format(StringUtil.PHOTOSETINFOURL,channel, setid);
					rst = HttpUtils.getResponseFromGetUrl(photoseturl, 30000,ImageSwitcherActivity.this);
				}
		        
		        JSONObject jsonobject = Tools.StringToJson(rst);
		        
		        if(null!=jsonobject){
		        	
		        	try {
		        		setname = jsonobject.getString("setname");
		        		setcoverurl = jsonobject.getString("cover");
		        		imgsum = jsonobject.getString("imgsum");
		        		seturl = jsonobject.getString("url");
		        		if(fromHead){//如果来自头条，那么需要对封面自己转换获得封面
		        		    clientcover = setcoverurl;
		        		    imageTitle = setname;
		        		}
						JSONArray jsonArray = jsonobject.getJSONArray("photos");
						
						Message msg = new Message();
					    msg.what = 1;
					    handler.sendMessage(msg);
						
						for(int index=0;index<jsonArray.length();index++){
							
							PhotoInfo photoinfo = new PhotoInfo();
							JSONObject jobj = jsonArray.getJSONObject(index);
							photoinfo.setImgtitle(jobj.getString("imgtitle"));
							String tempnote = jobj.getString("note");
							if(null==tempnote){
								tempnote = "";
							}else{
								try {
									tempnote = Tools.htmlDecoder(tempnote);
								} catch (Exception e) {
									
								}
							}
							photoinfo.setNote(tempnote);
							photoinfo.setOrgimgurl(jobj.getString("imgurl"));
							photoinfo.setImgurl(PicUtil.get3gImgurl(jobj.getString("imgurl"), 480, 480));
							photoinfo.setPhotohtml(jobj.getString("photohtml"));
							photoinfo.setSimgurl(jobj.getString("squareimgurl")); // 小图 simgurl
							photoinfo.setTimgurl(jobj.getString("timgurl"));
							photoinfo.setMydrawable(null);
							photoinfo.setPhotoid(jobj.getString("photoid"));
							photolist.add(photoinfo);
						}
						
						if(!"".equals(rst)){
	                        DBUtils.insertDataToPicTable(db, channel,setid, rst);
	                    }
						
		        	} catch (JSONException e) {
						e.printStackTrace();
						NeteaseHttpClient.removeCache(ImageSwitcherActivity.this, String.format(StringUtil.PHOTOSETINFOURL,channel, setid));
					}
	
		        	Message msg = handler.obtainMessage(9999);
                    msg.what = 9999;
                    handler.sendMessage(msg);
                    
                    
                    try {
                        if(!jsonobject.isNull("boardid"))
                            boardid = jsonobject.getString("boardid").trim();
                        if(!jsonobject.isNull("postid"))
                            postid = jsonobject.getString("postid").trim();
                        
                        int num = GetComments.getIamgeCommentNum(boardid, postid, ImageSwitcherActivity.this);
                        replyCountNum = num+"";
                        
                        JSONObject j = new JSONObject();
                        j.put(GetComments.P_TAG, "");
                        j.put(GetColumnsInfo.POSTID_TAG, postid);
                        
                        j.put("replyBoard",boardid);
                        j.put("setid",setid);
                        j.put("clientcover", clientcover);
                        j.put("imgsum", imgsum);
                        commentUrl = j.toString();
                        
                        if(fromCollect)
                            handler.sendEmptyMessage(11);
                        else
                            handler.sendEmptyMessage(10);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
		    
		        }else{
	    	
		        	Message msg = new Message();
		        	msg.what = 7;
		        	handler.sendMessage(msg);
		        }
				
			}
		}.start();
	}
	
	private CollectUtil cu;
	private int autoId;
	
	private ProgressDialog progressDialog;
	private View.OnClickListener button_download_ClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
		    
		    if(!isshowimg){
		        Toast.makeText(ImageSwitcherActivity.this, "已经设置不下载图片", Toast.LENGTH_SHORT).show();
		        return;
		    }

			if(PicUtil.isLocalPicExit(photolist.get(g_position).getPhotoid()+".jpg")) {
				WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(PicUtil.fitSizeImg(PicUtil.phototempDir+photolist.get(g_position).getPhotoid()+".jpg"));
				if(PicUtil.downloadBitmap(photolist.get(g_position).getPhotoid(), bitmapReference.get())) {
					Toast.makeText(ImageSwitcherActivity.this, "成功下载到相册", Toast.LENGTH_SHORT).show();
					sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"  
		                    + Environment.getExternalStorageDirectory())));
				}else Toast.makeText(ImageSwitcherActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
			} else {
				
				progressDialog.setMessage("正在下载图片...");
				progressDialog.show();
				
				new Thread() {
					public void run() {
						Drawable drawable = PicUtil.getPicturefromUrl(photolist.get(g_position).getImgurl(),ImageSwitcherActivity.this,isshowimg);
						if(null!=drawable){
							
							BitmapDrawable bd = (BitmapDrawable)drawable;
							if(null!=bd){
								WeakReference<Bitmap> bitmapReference = new WeakReference<Bitmap>(bd.getBitmap());			
								if(PicUtil.downloadBitmap(photolist.get(g_position).getPhotoid(), bitmapReference.get())) {
									handler.sendEmptyMessage(8);
								} else {
									handler.sendEmptyMessage(9);
								}
							}
			            			
						}else{
							handler.sendEmptyMessage(9);
							
						}
					}
				}.start();
			}

		}
	};
	
		
	private View.OnClickListener button_comment_ClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			new AlertDialog.Builder(ImageSwitcherActivity.this)
			.setTitle("分享")
				.setItems(new String[] {ImageSwitcherActivity.this.getResources().getString(R.string.share_to_weibo),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_sina),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_qq),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_renren),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_ydnote),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_sms),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_email),
						ImageSwitcherActivity.this.getResources().getString(R.string.share_to_other),
						},  
					new DialogInterface.OnClickListener(){
				
				@Override 
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					String account = set_prefs.getString("account", "");
					String sharetitle = setname;
					String shareurl = photolist.get(g_position).getOrgimgurl();
					String imgName = photolist.get(g_position).getPhotoid()+".jpg";
					
					Intent shareintent = new Intent();
					shareintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					shareintent.setClass(ImageSwitcherActivity.this, ShareToMicroBlog.class);
					Bundle bundle = new Bundle();
					bundle.putString("sharetitle", sharetitle);
					bundle.putString("shareurl", shareurl);
					bundle.putString("seturl", seturl);
					bundle.putBoolean("ispic", true);
					
					switch(arg1) {
						//网易微博
					case Constant.SHARE_NETEASE:
						bundle.putInt("sharetype", 0);
						shareintent.putExtras(bundle);
						ImageSwitcherActivity.this.startActivity(shareintent);
														
						break;
					//新浪微博
					case Constant.SHARE_SINA:
						bundle.putInt("sharetype", 1);
						bundle.putString("imgname", imgName);
						shareintent.putExtras(bundle);
						ImageSwitcherActivity.this.startActivity(shareintent);

						break;
					//腾讯微博
					case Constant.SHARE_QQ:									
						bundle.putInt("sharetype", 2);
						bundle.putString("imgname", imgName);
					    shareintent.putExtras(bundle);
					    ImageSwitcherActivity.this.startActivity(shareintent);
						break;	
					case Constant.SHARE_RENREN:                                  
                        bundle.putInt("sharetype", 3);
                        bundle.putString("imgname", imgName);
                        shareintent.putExtras(bundle);
                        ImageSwitcherActivity.this.startActivity(shareintent);
                        break;
                     // 有道笔记
					case Constant.SHARE_YDNOTE:               
						bundle.putInt("sharetype", 4);
						
						String shorturl = HttpUtils.getDocShortUrl("www",setcoverurl,ImageSwitcherActivity.this);
						bundle.putString("sharetitle", getShareHtml(shorturl, 4));
						bundle.putString("sharetitleyd", sharetitle);
						
						bundle.putString("imgname", imgName);
						shareintent.putExtras(bundle);
						ImageSwitcherActivity.this.startActivity(shareintent);
						break;
					case Constant.SHARE_SMS:
					    new AsyncTask<String, Integer, String>(){
                            @Override
                            protected String doInBackground(String... params) {
                                return HttpUtils.getDocShortUrl("www", params[0],ImageSwitcherActivity.this);
                            }
                            
                            @Override
                            protected void onPostExecute(String result) {
                                super.onPostExecute(result);
                                Intent sendIntent = new Intent(Intent.ACTION_VIEW);
                                sendIntent.putExtra("sms_body", ImageSwitcherActivity.this.getResources().getString(R.string.share_sms_pictext)
                                        + "<<"+setname+">>"
                                        + "图集地址:"+result
                                        +" "+ ImageSwitcherActivity.this.getResources().getString(R.string.share_with_u)+".");
                                sendIntent.setType("vnd.android-dir/mms-sms");
                                startActivity(sendIntent);
                            }
                        }.execute(seturl);
						break;
					case Constant.SHARE_EMAIL:
					    if(null!=sharelist && sharelist.size()>0){
					        try {                           
	                            
					            Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);                               
                                emailIntent.setType("message/rfc822");
                                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, 
                                        ImageSwitcherActivity.this.getResources().getString(R.string.share_email_pictitle));
                                
                                String html = getShareHtml(seturl, -1);
                                
                                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(html));
                                startActivity(Intent.createChooser(emailIntent, 
                                        ImageSwitcherActivity.this.getResources().getString(R.string.select_email_client)));                                        
	                            
	                        } catch (Exception e) {
	                            e.printStackTrace();
	                            Toast.makeText(ImageSwitcherActivity.this, 
	                                    ImageSwitcherActivity.this.getResources().getString(R.string.share_email_failure), 
	                                    Toast.LENGTH_SHORT).show();
	                        }
					    }else{
					       Toast.makeText(theContext, 
					               theContext.getResources().getString(R.string.share_email_noclient), Toast.LENGTH_SHORT).show();
					   }
						
	
						break;
					case Constant.SHARE_OTHER:
					    new AsyncTask<String, Integer, Map>(){

                            @Override
                            protected Map doInBackground(String... params) {
                                String shorturl = HttpUtils.getDocShortUrl("1",setcoverurl,ImageSwitcherActivity.this);
                                String wwwshorturl = HttpUtils.getDocShortUrl("2",seturl,ImageSwitcherActivity.this);
                                
                                Map map = new HashMap();
                                map.put("1", shorturl);
                                map.put("2", wwwshorturl);
                                return map;
                            }
                            
                            @Override
                            protected void onPostExecute(Map result) {
                                super.onPostExecute(result);
                                
                                String shorturl2 = (String)result.get("1");
                                String shortseturl2   = (String)result.get("2");
                                
                                Intent intent = new Intent(Intent.ACTION_SEND);
                                intent.setType("text/plain");
                                intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
                                intent.putExtra(Intent.EXTRA_TEXT,   ImageSwitcherActivity.this.getResources().getString(R.string.share_sms_pictext)
                                        + "<<"+setname+">>"
                                        + "图集地址:"+shortseturl2
                                        +" "+ ImageSwitcherActivity.this.getResources().getString(R.string.share_with_u) +" "+ shorturl2);
                                startActivity(Intent.createChooser(intent, getTitle()));
                            }
                     }.execute("");
						break;
					}
				}
			})
			.setNegativeButton("取消", null)
			.show();
		}
	};
		
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			
			
			switch(msg.what) {
			case 9999:
			    if (photolist == null || photolist.size() == 0) {
	                Toast.makeText(ImageSwitcherActivity.this, R.string.msg_loading_failed, Toast.LENGTH_SHORT)
	                        .show();
	            }
			    mImageViewer.setList(photolist, 0);
			    setCollectAttibute();
			        break;
			 
			case 0:
			    ImageView imageview = (ImageView)msg.obj;
			    if (imageview != null) {
			    Drawable drawable = (Drawable)imageview.getTag();
				if(null!=drawable){
				    imageview.setImageDrawable(drawable);
				}
			    }
				String tempdesc = photolist.get(g_position).getNote();
				if(null==tempdesc || "".equals(tempdesc)){
					text_imgtitle.setText(photolist.get(g_position).getImgtitle());  
				}else{
					text_imgtitle.setText(tempdesc);
				}
				if("".equalsIgnoreCase(""+text_imgtitle.getText())){
				    hide_open_desc.setVisibility(View.INVISIBLE);
				}else{
				    hide_open_desc.setVisibility(View.VISIBLE);
				}
		        button_download.setEnabled(true);
		        button_collect.setEnabled(true);
		        button_comment.setEnabled(true);
				
		        text_setname.setText(setname);
                text_imgsum.setText((g_position+1)+"/"+imgsum);
				break;
			case 1:
				text_setname.setText(setname);
        		text_imgsum.setText((g_position+1)+"/"+imgsum);   
				break;
			case 2:
			    LinearLayout progress = (LinearLayout)msg.obj;
			    int f = msg.arg1; 
			    if(f==0){
			        progress.setVisibility(View.VISIBLE);
			    }else{
			        progress.setVisibility(View.GONE);
			    }
			    
				break;
			case 4:
				new SaveBitmapTask(photolist.get(g_position).getMydrawable(), photolist.get(g_position).getPhotoid()).execute("");
				break;
			case 5:
				new SaveBitmapTask(photolist.get(g_position).getMydrawable(), photolist.get(g_position).getPhotoid()).execute("");
				break;
			case 6:
			    
				break;
			case 7:
				Toast.makeText(ImageSwitcherActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
				ImageSwitcherActivity.this.finish();
				break;
			case 8:
				if(progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();
				Toast.makeText(ImageSwitcherActivity.this, "成功下载到相册", Toast.LENGTH_SHORT).show();				
				break;
			case 9:
				if(progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();
				if(isshowimg){
					Toast.makeText(ImageSwitcherActivity.this, "保存图片失败", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(ImageSwitcherActivity.this, "已经设置不下载图片", Toast.LENGTH_SHORT).show();
				}
				break;
				
			case 10:
				if("-1".equals(replyCountNum)){
					detailPageReply.setVisibility(View.GONE);
				}else{
					detailPageReply.setVisibility(View.VISIBLE);
					detailPageReply.setText(replyCountNum + "跟贴");
				}
				
				
				break;
			case 11:
                switchNewsAndComments(true);
                break;
			case 15:
				if(progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss();
				if(msg.obj != null) {
					if (msg.obj.toString().equals("1")) {
						Toast.makeText(ImageSwitcherActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
						replyEditText.setText("");
					} else if (!msg.obj.toString().equals("")) {
						//Toast.makeText(ImageSwitcherActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
						Toast.makeText(ImageSwitcherActivity.this, "发表失败" /*,原因:"+msg.obj.toString()*/, Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(ImageSwitcherActivity.this, "发表失败", Toast.LENGTH_SHORT).show();
					}

					if (imm != null) {
                        imm.hideSoftInputFromWindow(replyEditText.getWindowToken(), 0);
                    }
                    top_relative.setVisibility(View.VISIBLE);
                    bottom_buttonlayout.setVisibility(View.VISIBLE);
                    reply_edittext_layout.setVisibility(View.GONE);

				} else {
					Toast.makeText(ImageSwitcherActivity.this, "发表失败", Toast.LENGTH_SHORT).show();
				}
			
				break;
			}
		}
	};

	public String getPhotosetJson(String channel,String setid){
		
		String json = "";
		
		String sql = "select * from " + NewsSQLiteOpenHelper.PIC_TABLE + 
		" where "+NewsSQLiteOpenHelper.PIC_SETID+"='"+setid+"' and "+NewsSQLiteOpenHelper.PIC_CHANNEL+"='"+channel+"' order by "+NewsSQLiteOpenHelper.PIC_AUTO_ID+" desc limit 0,1";
		Cursor cursor = db.rawQuery(sql,null);
		this.startManagingCursor(cursor);
		
		if(cursor != null && cursor.getCount()!= 0) {
			
			for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext())
    		{
				json = cursor.getString(cursor.getColumnIndex(NewsSQLiteOpenHelper.PIC_JSON));
				
				if(null==json) json = "";
    		}
		}
		
		return json;
	}
		
	class SaveBitmapTask extends AsyncTask<String, Integer, String> {
		private final WeakReference<Drawable> drawableReference;
		private final String filename;
		
		public SaveBitmapTask(Drawable drawable, String name) {
			drawableReference = new WeakReference<Drawable>(drawable);
			filename = name;
		}
		
		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			if(null!=drawableReference){
				BitmapDrawable bd = (BitmapDrawable)drawableReference.get();
				if(null!=bd){
					Bitmap mBitmap = bd.getBitmap();					
					PicUtil.saveMyBitmap(filename, mBitmap);

				}
				
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			photolist.get(g_position).setMydrawable(null);
		}

	}
	
	   
    @Override
    public void onItemClick(int position) {
        if (reply_edittext_layout.getVisibility() == View.VISIBLE) {
            reply_edittext_layout.setVisibility(View.GONE);
            bottom_buttonlayout.setVisibility(View.VISIBLE);
            bottom_framelayout.setVisibility(View.VISIBLE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(replyEditText.getWindowToken(), 0);
            }
        } else {
            if (showtoolbar) {

                top_relative.setVisibility(View.INVISIBLE);
                imagerandombar.setVisibility(View.INVISIBLE);

                if (config == Configuration.ORIENTATION_LANDSCAPE) {
                    bottom_framelayout.setVisibility(View.GONE);
                } else {
                    bottom_framelayout.setVisibility(View.INVISIBLE);
                }

            } else {
                top_relative.setVisibility(View.VISIBLE);
                if (reply_edittext_layout.getVisibility() == View.GONE) {
                    bottom_buttonlayout.setVisibility(View.VISIBLE);
                }
                imagerandombar.setVisibility(View.VISIBLE);
                if (config != Configuration.ORIENTATION_LANDSCAPE)
                    bottom_framelayout.setVisibility(View.VISIBLE);
            }
            showtoolbar = !showtoolbar;
        }

    }

    @Override
    public void onItemSelected(int position) {
        g_position = position;
        handler.handleMessage(handler.obtainMessage(0));
    }
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		 try {
            moreMap.clear();
             docIDListMap.clear();
             docIDList.clear();
             specailIDList.clear();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}

    //	private PopupWindow menuWindow;
	private boolean menu_display = false;
	private LinearLayout menu_refresh;
	private LinearLayout menu_mycollect;
	private LinearLayout menu_comment;
	
	private View menu_1;
	private View menu_2;
	
	private void setMenu() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.detail_page_menu, null);			
		menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //后两个参数是width和height
		
		menuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		menu_1 = layout.findViewById(R.id.menu_tabrow_1);
		menu_2 = layout.findViewById(R.id.menu_tabrow_2);
		menu_refresh = (LinearLayout)layout.findViewById(R.id.menu_second_refresh);
		menu_mycollect = (LinearLayout)layout.findViewById(R.id.menu_my_collect);
		menu_comment = (LinearLayout)layout.findViewById(R.id.menu_child_comment);
		
		menu_refresh.setVisibility(View.VISIBLE);
		menu_mycollect.setVisibility(View.VISIBLE);
		menu_comment.setVisibility(View.VISIBLE);
		
		menu_refresh.setOnClickListener(menuRefreshLinstener);
		menu_mycollect.setOnClickListener(menuMyCollectListener);
		menu_comment.setOnClickListener(menuMyCommentListener);
	}

	@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        menu_display = false;
    }
	
	/** 系统菜单定义 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getRepeatCount()>1){
			return super.onKeyDown(keyCode, event);
		}
		if(menu_display){
			menuWindow.dismiss();
			menu_display = false;
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(fromCollect){
				if(detailPageOriginal.getVisibility() == View.VISIBLE) {
				    switchNewsAndComments(true);
					return true;
				}
			}else{
				if(detailPageComments.getVisibility() == View.VISIBLE) {
				    switchNewsAndComments(false);
					return true;
				}
			}
		}else if(keyCode == KeyEvent.KEYCODE_MENU){
			View myRoot = (View)ImageSwitcherActivity.this.findViewById(R.id.container);
			if(!menuWindow.isShowing()){
				menuWindow.showAtLocation(myRoot, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
				menu_display = true;
				
				menu_1.setVisibility(View.GONE);
				menu_2.findViewById(R.id.menu_child_textsize).setVisibility(View.GONE);
				
			}else{
				//如果当前已经为显示状态，则隐藏起来
				menuWindow.dismiss();
				menu_display = false;
			}
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	private int config = 1;
	/**横竖屏切换*/
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    
	    
		
		config = newConfig.orientation;
		if(isComment){
		    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);			
		}else{
			if(config == Configuration.ORIENTATION_LANDSCAPE){ // 横屏
			   
				bottom_framelayout.setVisibility(View.GONE);
			}else{ // 竖屏
			    
			    if(showtoolbar){
			        bottom_framelayout.setVisibility(View.VISIBLE);
			    }
				
			}
		}
		
		
		super.onConfigurationChanged(newConfig);
	}
	
	
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(menuWindow.isShowing()){ // 点击屏幕时，隐藏菜单
			menuWindow.dismiss();
			menu_display = false;
		}
		boolean result = false;
		try {
			result = super.dispatchTouchEvent(ev);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/** 我的收藏 */	
	private View.OnClickListener menuMyCollectListener = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			menuWindow.dismiss();
			menu_display = false;
			Intent intent = new Intent();
			intent.setClass(ImageSwitcherActivity.this, CollectActivity.class);
			startActivity(intent);
		}
	};
	
	/**我的跟帖*/
	private View.OnClickListener menuMyCommentListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			menuWindow.dismiss();
			menu_display = false;
			Intent intent = new Intent();
			intent.setClass(ImageSwitcherActivity.this, MyCommentsActivity.class);
			startActivity(intent);
		}
	};
	
	/**刷新*/
	private View.OnClickListener menuRefreshLinstener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			menuWindow.dismiss();
			menu_display = false;
			isRefresh = true;
			if(isComment){
			    if (detailPageComments.getVisibility() == View.VISIBLE) {
	                CommentFragment fragment = (CommentFragment) getSupportFragmentManager()
	                        .findFragmentByTag("detail_comment");
	                if (fragment != null) {
	                    fragment.refresh();
	                }
	            }
			}else{
				
				if(null!=photolist && photolist.size()>0){
				    g_position = 0;
				    mImageViewer.refreshCurrent();
				    }
			}     	
		}
	};
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
        if (detailPageComments.getVisibility() == View.VISIBLE) {
            CommentFragment fragment = (CommentFragment) getSupportFragmentManager()
                    .findFragmentByTag("detail_comment");
            if (fragment != null && fragment.dispatchKeyEvent(event)) {
                return true;
            }
        }
		if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {			
			
			if(reply_edittext_layout.getVisibility() == View.VISIBLE) {
				bottom_buttonlayout.setVisibility(View.VISIBLE);
				reply_edittext_layout.setVisibility(View.GONE);
		        if (imm != null) {
		        	imm.hideSoftInputFromWindow(replyEditText.getWindowToken(), 0);
		        }
		        if(top_relative.getVisibility() == View.GONE) {
		        	top_relative.startAnimation(slideTopIn);
		        }	
		        return true;
			} 			
		}
		return super.dispatchKeyEvent(event);
	}
	
	private int currentSizeId = 2;
    private int lastSizeId = 2;
	public float getLastTextSize(){
        float rst = 18.0f;
        if(0==lastSizeId){
            rst =  26.0f;
        }else if(1==lastSizeId){
            rst =  22.0f;
        }else if(2==lastSizeId){
            rst = 16.0f;
        }else if(3==lastSizeId){
            rst = 14.0f;
        }
        
        return rst;
    }
	
	public void onApplyTheme() {
        super.onApplyTheme();
        themeSettingsHelper.setViewBackgroudColor(this, R.id.container, R.color.main_bg_color);
        themeSettingsHelper.setViewBackgroud(this,R.id.detail_page_reply_frame,R.drawable.reply_frame_bk);
        themeSettingsHelper.setImageViewSrc(this,R.id.reply_img_button,R.drawable.image_edit_bk);
        themeSettingsHelper.setViewBackgroud(this, R.id.common_comments_title_layout, R.drawable.top_background);
        themeSettingsHelper.setViewBackgroud(this, R.id.show_comments_back_original, R.drawable.topcomment_column);
        themeSettingsHelper.setViewBackgroud(this,R.id.reply_layout,R.drawable.reply_frame_bk);
        themeSettingsHelper.setImageViewSrc(this, button_comment, R.drawable.share_button_selector);
        themeSettingsHelper.setViewBackgroud(this, reply_edittext_layout, R.drawable.reply_frame_bk);
        themeSettingsHelper.setViewBackgroud(this, reply_button, R.drawable.netease_big_button);
        themeSettingsHelper.setTextViewColor(this, reply_button, R.color.list_title_color);
        
        themeSettingsHelper.setTextViewColor(this, R.id.show_comments_back_original, R.color.top_image_title_color);
        themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.top_image_title_color);
        themeSettingsHelper.setTextViewColor(this, (TextView)detailPageComments.findViewById(R.id.top_main_text), R.color.top_image_title_color);

        themeSettingsHelper.setImageViewSrc(this, (ImageView)detailPageComments.findViewById(R.id.top_id_image), R.drawable.netease_top);
        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.netease_top_);
        themeSettingsHelper.setViewBackgroud(this, detailPageComments.findViewById(R.id.top_main_bottom), R.drawable.top_background);
        themeSettingsHelper.setTextViewColor(this, detailPageReply, R.color.main_title_color);
        themeSettingsHelper.setImageViewSrc(this, button_download, R.drawable.download_selector);
        
        // 菜单夜间模式
        themeSettingsHelper.setViewBackgroudColor(this, menu_2, R.color.menu_layout_bg_color);
        themeSettingsHelper.setViewBackgroud(this, menu_refresh, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_refresh.getChildAt(1), R.color.menu_text_color);
        themeSettingsHelper.setViewBackgroud(this, menu_mycollect, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_mycollect.getChildAt(1), R.color.menu_text_color);
        themeSettingsHelper.setViewBackgroud(this, menu_comment, R.drawable.menu_background);
        themeSettingsHelper.setTextViewColor(this, (TextView)menu_comment.getChildAt(1), R.color.menu_text_color);

        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_from_comment, R.drawable.go_back);
        themeSettingsHelper.setImageViewSrc(this, R.id.go_back_from_original, R.drawable.night_go_back);
        
        CommentFragment fragment = (CommentFragment)getSupportFragmentManager().findFragmentByTag("detail_comment");
        if (fragment != null) {
            fragment.applyTheme();
        }
        
	}
}
